package com.scenic.user.service.service.servicelmpl;

import com.model.dto.LoginDto;
import com.model.dto.RegisterDto;
import com.model.entity.SysUser;
import com.model.vo.LoginVo;
import com.scenic.user.service.mapper.SysUserMapper;
import com.scenic.user.service.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

// com.atguigu.spzx.manager.service.impl
@Service
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;


    @Override
    public LoginVo login(LoginDto loginDto) {
        //根据用户电话或邮箱查询用户
        SysUser sysUser = sysUserMapper.selectByPhone(loginDto.getUserName());
        if (sysUser == null) {
            sysUser = sysUserMapper.selectByEmail(loginDto.getUserName());
            if (sysUser == null) {
                throw new RuntimeException("用户不存在");
            }
        }

        String inputPassword = loginDto.getPassword();
        String md5InputPassword = DigestUtils.md5DigestAsHex(inputPassword.getBytes());
        if (!md5InputPassword.equals(sysUser.getPassword())) {
            throw new RuntimeException("用户名或者密码错误");
        }

           // 构建响应结果对象
        LoginVo loginVo = new LoginVo();
//        loginVo.setToken(token);
        loginVo.setRefresh_token("");

        // 返回
        return loginVo;
    }

    @Override
    public void register(RegisterDto registerDto) {
        //查询数据库中是否存在该用户
        SysUser sysUser = sysUserMapper.selectByPhone(registerDto.getPhone());
        if (sysUser != null) {
            throw new RuntimeException("用户已存在");
        }
        //添加用户
        SysUser sysUser1 = new SysUser();
        //密码加密
        String md5Password = DigestUtils.md5DigestAsHex(registerDto.getPassword().getBytes());
        sysUser1.setPassword(md5Password);
        sysUser1.setPhone(registerDto.getPhone());
        sysUser1.setEmail(registerDto.getEmail());
        sysUserMapper.insert(sysUser1);
        return;
    }

    @Override
    public SysUser getUserInfo(String userId) {
        // 查询数据库中用户信息
        SysUser sysUser = sysUserMapper.selectById(userId);
        return sysUser;
    }
}
